package com.silence.gankio.mvvm.viewModel

import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.silence.gankio.core.net.HttpUtil
import com.silence.gankio.net.BaseBindingObserver
import com.silence.gankio.service.GankIoService
import com.silence.gankio.service.IsoyuService
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


open class BaseViewModel : ViewModel() {

    val dataLoading by lazy { MutableLiveData<Boolean>() }

    val errorMsg by lazy { MutableLiveData<String>() }

    protected val mGankIoService by lazy { HttpUtil().getService(GankIoService::class.java) }
    protected val mIsoyuService by lazy { HttpUtil().getService(IsoyuService::class.java) }

    private val mCompositeDisposable = CompositeDisposable()

    fun applyDisposable(d: Disposable) {
        mCompositeDisposable.add(d)
    }

    protected fun <T> load(showLoadingUI: Boolean = true, observable: Observable<T>, observer: BaseBindingObserver<T>) {
        if (showLoadingUI) {
            dataLoading.value = true
        }
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer)
    }

    override fun onCleared() {
        super.onCleared()
        mCompositeDisposable.clear()
    }
}